SwaggerModule.createDocument, setup 옵션 {nestjs}

📘 NestJS SwaggerModule 설정 가이드

NestJS는 @nestjs/swagger 모듈을 통해 OpenAPI(Swagger) 문서를 쉽게 생성하고, UI로 제공할 수 있습니다. 이 문서에서는 SwaggerModule.createDocumentSwaggerModule.setup 사용법을 다룹니다.


1. SwaggerModule.createDocument(app, config[, options])

NestJS 애플리케이션에서 swagger.json을 생성할 때 사용합니다.

💡 주요 구성 요소: DocumentBuilder

DocumentBuilder는 Swagger 설정을 위한 체이닝 방식의 설정자입니다.

const config = new DocumentBuilder()
  .setTitle('Racket Time API')                     // 문서 제목
  .setDescription('라켓 타임 스웨거')              // 설명
  .setVersion('0.0.1')                              // 버전
  .addTag('Auth', '인증 관련 API')                 // 태그로 API 그룹화
  .addBearerAuth(
    {
      type: 'http',
      scheme: 'bearer',
      bearerFormat: 'JWT',
      name: 'Authorization',
      in: 'header',
    },
    'Authorization',                                // Security name (참고용)
  )
  .build();

📁 문서 생성

const document = SwaggerModule.createDocument(app, config, {
  // 포함할 모듈만 지정하거나, extraModels로 수동 모델 등록 가능
  // include: [UserModule, AuthModule],
  // extraModels: [UserEntity, RoleEnum],
});
fs.writeFileSync(SWAGGER_FILE_PATH, JSON.stringify(document));

2. SwaggerModule.setup(path, app, document[, options])

Swagger UI를 특정 경로에 세팅할 때 사용합니다.

SwaggerModule.setup('/docs', app, document, {
  swaggerOptions: {
    docExpansion: 'none', // 'none', 'list', 'full'
    persistAuthorization: true, // 페이지 새로고침 후에도 인증 유지
    displayRequestDuration: true, // 각 요청별 응답 시간 표시
  },
  customSiteTitle: 'Racket Time API Docs',
});

🔧 전체 스니펫 예제

import { INestApplication } from '@nestjs/common';
import { DocumentBuilder, SwaggerModule } from '@nestjs/swagger';
import fs from 'fs';
import { SWAGGER_FILE_PATH } from '@/constant';

export const setupSwagger = (app: INestApplication) => {
  const config = new DocumentBuilder()
    .setTitle('Racket Time API')
    .setDescription('라켓 타임 API 명세서입니다.')
    .setVersion('0.0.1')
    .addTag('Auth', '인증 관련 API')
    .addTag('User', '유저 관련 API')
    .addBearerAuth(
      {
        type: 'http',
        scheme: 'bearer',
        bearerFormat: 'JWT',
        name: 'Authorization',
        in: 'header',
      },
      'Authorization',
    )
    .build();

  const document = SwaggerModule.createDocument(app, config);
  fs.writeFileSync(SWAGGER_FILE_PATH, JSON.stringify(document));

  SwaggerModule.setup('/docs', app, document, {
    swaggerOptions: {
      docExpansion: 'none',
      persistAuthorization: true,
      displayRequestDuration: true,
    },
    customSiteTitle: 'Racket Time API Docs',
  });
};

📎 참고사항